package com.tanhua.server.init;

import com.tanhua.domain.db.QuizQuestion;
import com.tanhua.dubbo.api.db.QuizQuestionApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @Author:chenda
 * @Date:2021/8/24 16:46
 */

/**
 * spring启动后则自动查询问题表，并存入redis中
 */
@Slf4j
@Component
public class QuestionInit implements ApplicationRunner {

    //redis中存储问题的键
    private final String questionKey = "QUIZ_QUESTION_ITEM_";

    @Reference
    private QuizQuestionApi quizQuestionApi;

    @Autowired
    private RedisTemplate<Object, Object> redisTemplate;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.debug("--------正在加载问题库-------------");
        List<QuizQuestion> questions = quizQuestionApi.getAllQuestions();
        //如果有数据则存入redis
        if (CollectionUtils.isNotEmpty(questions)) {
            for (QuizQuestion question : questions) {
                redisTemplate.boundValueOps(questionKey + question.getNum()).set(question);
            }
        }
        log.debug("----------------问题加载到redis成功！----------------");
    }
}
